package com.sgb.kjwl.view.ui.activity.pick;

import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.tabs.TabLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.ScrollBoundaryDecider;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityPickExpertListBinding;
import com.sgb.kjwl.di.pick.DaggerPickFragComponent;
import com.sgb.kjwl.di.pick.PickFragModule;
import com.sgb.kjwl.model.entity.pick.PickExpertListEntity;
import com.sgb.kjwl.view.ui.adapter.pick.PickExpertAdapter;
import com.sgb.kjwl.view.widget.PickHallBidingPopWindow;
import com.sgb.kjwl.view.widget.pick.PickPopWindowView;
import com.sgb.kjwl.viewmodel.pick.PickExpertListModel;
import com.sgb.link.utils.SizeUtils;
import com.sgb.zhaocai.widget.threefliter.ZCThreeLevelFilterWindow;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.util.MToast;
import com.swgk.core.util.PickSelectEntity;
import com.swgk.core.view.areapopup.AddressEntity;
import com.swgk.core.view.areapopup.GoodsSourceLocationEntity;
import com.swgk.core.view.areapopup.ThreeLevelAreaWindow;
import com.swgk.core.view.selection.CommonPopEntity;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/**
 * 专家库页面
 **/

public class PickExpertListActivity extends AppActivity {

    @Inject
    PickExpertListModel viewModel;
    private ActivityPickExpertListBinding binding;

    private boolean isSearching = false;
    private String searchName = "";

    private ThreeLevelAreaWindow mAddressPop;
    private ZCThreeLevelFilterWindow majorCategory;
    private PickHallBidingPopWindow typePopWindow;

    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> scrData;
    private List<PickSelectEntity> typeData = new ArrayList<>();
    private List<PickSelectEntity> tabLayoutData = new ArrayList<>();
    private List<CommonPopEntity> commonlist;

    //省
    private String areaCode;
    private String areaName;
    private String cityNo;
    private String typeNo = "";
    private String typeName;
    private String majorNo = "";
    private String majorName;
    private String professionNo;

    private boolean isEnableLoadMore = false; //是否可以上拉加载
    private boolean isLoadMore = false;
    private int page = 1;
    private PickExpertAdapter pickExpertAdapter;

    public static void start(Context context) {
        Intent intent = new Intent(context, PickExpertListActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerPickFragComponent.builder()
                .appComponent(appComponent)
                .pickFragModule(new PickFragModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void initView() {
        super.initView();
        binding = DataBindingUtil.setContentView(this, R.layout.activity_pick_expert_list);

        binding.includeTitle.titleView.setText("专家库");
        binding.includeTitle.rightView.setText("新增");

        binding.includeSearch.etView.setHint("请输入专家名称");
        binding.includeSearch.etView.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        binding.includeSearch.etView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (isSearching) return true;
                if (TextUtils.isEmpty(binding.includeSearch.etView.getText().toString())) {
                    MToast.showToast(PickExpertListActivity.this, "请输入专家名称");
                    return true;
                }
                if (searchName.equals(binding.includeSearch.etView.getText().toString())) {
                    MToast.showToast(PickExpertListActivity.this, "请输入不同的搜索内容");
                    return true;
                }
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                    isSearching = true;
                    searchName = binding.includeSearch.etView.getText().toString();
                    initFilterData();
                }
                return false;
            }
        });

        binding.includeSearch.etView.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s)) {
                    binding.includeSearch.tvSearchDelete.setVisibility(View.GONE);
                } else {
                    binding.includeSearch.tvSearchDelete.setVisibility(View.VISIBLE);
                }
            }
        });

        binding.includeTitle.ivBack.setOnClickListener(this);
        binding.includeTitle.rightView.setOnClickListener(this);
        binding.includeSearch.tvSearchDelete.setOnClickListener(this);
        binding.includeSearch.searchText.setOnClickListener(this);
        binding.tvType.setOnClickListener(this);
        binding.tvAddress.setOnClickListener(this);
        binding.tvMajorCategory.setOnClickListener(this);
        binding.imgBackTop.setOnClickListener(this);

        binding.tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                professionNo = tabLayoutData.get(tab.getPosition()).getNo();
                initFilterData();

                if (tab != null && tab.getCustomView() != null) {
                    TextView tabSelect = tab.getCustomView().findViewById(R.id.tv_tab_item_textview);
                    tabSelect.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                    tabSelect.setTextColor(getResources().getColor(R.color.color_main));
                    tabSelect.setTextSize(14);
                    tabSelect.invalidate();
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                if (tab != null && tab.getCustomView() != null) {
                    TextView tabSelect = tab.getCustomView().findViewById(R.id.tv_tab_item_textview);
                    tabSelect.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
                    tabSelect.setTextColor(getResources().getColor(R.color.color_tab_two));
                    tabSelect.setTextSize(14);
                    tabSelect.invalidate();
                }
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }

        });

        typePopWindow = new PickHallBidingPopWindow(getActivity());
        typePopWindow.setBgView(binding.grayLayout);
        typePopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
                typeName = ((PickSelectEntity) key1).getProjectscale();
                typeNo = ((PickSelectEntity) key1).getNo();
                if ("不限".equals(typeName)) {
                    typeName = "所属类别";
                }
                updateChooseTextStatus(binding.tvType, (Integer) key3, typeName);
                initFilterData();

            }
        });
        typePopWindow.setOnDisMissClick(new BasePopWindow.OnDisMiss() {
            @Override
            public void disMiss() {
                updateChooseTextStatus(binding.tvType, "所属类别".equals(typeName) ? 0 : 1, typeName);
            }
        });
        initAddressPopup();
        initCateGoryPopup();

        int screenHeight = SizeUtils.getScreenHeight(getActivity());
        binding.scrollview.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                RecyclerView.LayoutManager layoutManager = binding.recyclerView.getLayoutManager();
                View view = layoutManager.findViewByPosition(0);
                if (view != null) {
                    int height = view.getMeasuredHeight();
                    int headHeight = screenHeight - binding.llContainer.getHeight();
                    int gonePosition = 10 - (headHeight / view.getHeight());
                    binding.imgBackTop.setVisibility((height * gonePosition) > scrollY ? View.GONE : View.VISIBLE);
                }
            }
        });

        binding.swipeRefresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                isLoadMore = true;
                viewModel.findPage(page, professionNo, majorNo, typeNo, areaCode, cityNo, searchName);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                initFilterData();
                binding.swipeRefresh.finishRefresh(300);
            }
        });
        //解决 在实现 上拉加载更多 和 下拉刷新 时  遇到item不在顶端就执行了刷新的方法和数据item没有填满屏幕也执行了加载更多
        binding.swipeRefresh.setScrollBoundaryDecider(new ScrollBoundaryDecider() {
            @Override
            public boolean canRefresh(View content) {
                if (binding.scrollview == null) return false;
                if (binding.scrollview.computeVerticalScrollOffset() == 0)
                    return true;
                return false;
            }

            @Override
            public boolean canLoadMore(View content) {
                if (binding.scrollview == null) return false;
                //获取recyclerView的高度
                binding.scrollview.getHeight();
                //整个View控件的高度
                int scrollRange = binding.scrollview.computeVerticalScrollRange();
                //当前屏幕之前滑过的距离
                int scrollOffset = binding.scrollview.computeVerticalScrollOffset();
                //当前屏幕显示的区域高度
                int scrollExtent = binding.scrollview.computeVerticalScrollExtent();
                int height = binding.scrollview.getHeight();
                if (height > scrollRange) {
                    return false;
                }
                if (isEnableLoadMore && scrollRange <= scrollOffset + scrollExtent) {
                    return true;
                }
                return false;
            }
        });

        if (pickExpertAdapter == null) {
            pickExpertAdapter = new PickExpertAdapter(this, null);
        }
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        binding.recyclerView.setLayoutManager(layoutManager);
        DividerItemDecoration divider = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(this, R.drawable.shape_list_divide));
        binding.recyclerView.addItemDecoration(divider);
        binding.recyclerView.setAdapter(pickExpertAdapter);
        pickExpertAdapter.setOnItemClick(new AdapterOnItemClick<PickExpertListEntity>() {
            @Override
            public void onItemClick(PickExpertListEntity pickExpertListEntity, int position) {
                viewModel.detail(pickExpertListEntity.getNo());
            }
        });
        pickExpertAdapter.onIChildClick(new PickExpertAdapter.IChildClick() {
            @Override
            public void onEdit(PickExpertListEntity pickExpertListEntity) {
                PickExpertEditActivity.start(getActivity(),pickExpertListEntity.getNo());
            }

            @Override
            public void onDelete(PickExpertListEntity pickExpertListEntity, int position) {
                viewModel.delete(pickExpertListEntity.getNo(),position);
            }
        });

    }

    @Override
    protected void init() {
        super.init();
        initData();
    }

    private void initFilterData(){
        page = 1;
        isLoadMore = false;
        viewModel.findPage(page, professionNo, majorNo, typeNo, areaCode, cityNo, searchName);
    }

    private void initData() {
        viewModel.getProfessionSelect();
        viewModel.getMajorCategorySelect();
        viewModel.getCategoryTypeSelect();
        viewModel.getProvinceData();
    }

    private void initCateGoryPopup() {
        majorCategory = new ZCThreeLevelFilterWindow(this);
        majorCategory.setBgView(binding.grayLayout);
        majorCategory.setLineVisibility(View.GONE);
        majorCategory.setOnResultClick(new ZCThreeLevelFilterWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
                CommonPopEntity pickResultProject1 = (CommonPopEntity) key1;
                CommonPopEntity pickResultProject2 = (CommonPopEntity) key2;
                CommonPopEntity pickResultProject3 = (CommonPopEntity) key3;
                if (!"不限".equals(pickResultProject1.getTypeName())) {
                    majorName = pickResultProject1.getTypeName();
                    majorNo = pickResultProject1.getNo();
                } else {
                    majorName = "";
                    majorNo = "";
                    majorCategory.setData(commonlist, 0);
                }
                if (pickResultProject2 != null && !TextUtils.isEmpty(pickResultProject2.getTypeName())) {
                    if (!"全部".equals(pickResultProject2.getTypeName())) {
                        majorName = pickResultProject2.getTypeName();
                        majorNo = pickResultProject2.getNo();
                    } else {
                        majorName = "";
                        majorNo = "";
                    }
                }
                if (pickResultProject3 != null && !TextUtils.isEmpty(pickResultProject3.getTypeName())) {
                    if (!"全部".equals(pickResultProject3.getTypeName())) {
                        majorName = pickResultProject3.getTypeName();
                        majorNo = pickResultProject3.getNo();
                    } else {
                        majorName = "";
                        majorNo = "";
                    }
                }
                updateChooseTextStatus(binding.tvMajorCategory, TextUtils.isEmpty(majorNo) ? 0 : 1, majorName);
                initFilterData();
            }

            @Override
            public void reset() {
                majorNo = "";
                majorName = "";
                majorCategory.setData(commonlist, 0);
                updateChooseTextStatus(binding.tvMajorCategory, TextUtils.isEmpty(majorNo) ? 0 : 1, majorName);
                initFilterData();
            }
        });
        majorCategory.setOnDismissListener(() -> {
            updateChooseTextStatus(binding.tvMajorCategory, TextUtils.isEmpty(majorNo) ? 0 : 1, majorName);
        });
    }

    private void initAddressPopup() {
        mAddressPop = new ThreeLevelAreaWindow(getActivity());
        mAddressPop.setMemberHeight();
        mAddressPop.setCitySingle();
        mAddressPop.setProvinceSingle();
        mAddressPop.setShowSimpleName(true);
        mAddressPop.setOnlyShowProAndCity(true);
        mAddressPop.setAllSingleSelect(true);
        mAddressPop.setThreeListIsGone(true);
        mAddressPop.setBgView(binding.grayLayout);
        mAddressPop.setOnResultClick(new ThreeLevelAreaWindow.OnResultClickProxy() {
            @Override
            protected void result(GoodsSourceLocationEntity entity) {
                areaCode = entity.getProvinceNo();
                if (!TextUtils.isEmpty(entity.getProvinceNo())) {
                    areaName = entity.getProvinceName();
                    areaCode = entity.getProvinceNo();
                    cityNo = "";
                    if ("0".equals(areaCode)) {
                        areaName = "工作地区";
                    }

                    updateChooseTextStatus(binding.tvAddress, 1, areaName);
                    if (!TextUtils.isEmpty(entity.getCityNo())) {
                        cityNo = entity.getCityNo();
                        areaName = entity.getCityName();
                        mAddressPop.setData(scrData, true);
                        updateChooseTextStatus(binding.tvAddress, 1, areaName);
                    }
                } else {
                    areaName = "工作地区";
                    areaCode = "";
                    cityNo = "";
                    updateChooseTextStatus(binding.tvAddress, 0, areaName);
                }
                initFilterData();
            }
        });
        mAddressPop.setOnDismissListener(() -> {
            updateChooseTextStatus(binding.tvAddress, "工作地区".equals(areaName) ? 0 : 1, areaName);
        });
    }

    public void getExpertData(List<PickExpertListEntity> list) {
        isSearching = false;
        if (list != null) {
            isEnableLoadMore = list.size() >= 10;
        }
        binding.swipeRefresh.finishLoadMore(true);
        if (isLoadMore) {
            if (list.size() > 0) {
                pickExpertAdapter.addDatas(list);
            }
            binding.recyclerView.setVisibility(View.VISIBLE);
        } else {
            if (list.size() > 0) {
                binding.recyclerView.setVisibility(View.VISIBLE);
                binding.emptyView.setVisibility(View.GONE);
                pickExpertAdapter.setDatas(list);
                binding.imgBackTop.setVisibility(View.GONE);
                binding.recyclerView.scrollToPosition(0);
                binding.scrollview.scrollTo(0, 0);
            } else {
                pickExpertAdapter.setDatas(null);
                binding.recyclerView.setVisibility(View.GONE);
                binding.emptyView.setVisibility(View.VISIBLE);
            }
        }
    }

    public void setProvinceDatas(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {
        if (data != null && data.size() > 0) {
            scrData = data;
            mAddressPop.setData(scrData, true);
        } else {
            viewModel.getProvinceData();
        }
    }

    /**
     * 专家库列表专家职称筛选框
     */
    public void setTabLayoutData(List<PickSelectEntity> data) {
        if (data == null) return;
        tabLayoutData.clear();
        tabLayoutData.addAll(data);
        for (int i = 0; i < tabLayoutData.size(); i++) {
            binding.tabLayout.addTab(binding.tabLayout.newTab(), false);
            binding.tabLayout.getTabAt(i).setCustomView(R.layout.tab_item_textview);

            View view = binding.tabLayout.getTabAt(i).getCustomView();
            TextView tv = view.findViewById(R.id.tv_tab_item_textview);
            tv.setText(tabLayoutData.get(i).getProjectscale());
            tv.setTextSize(14);
            tv.setTextColor(getResources().getColor(R.color.color_tab_two));
        }
        binding.tabLayout.getTabAt(0).select();
    }

    /**
     * 专家库列表评标专业筛选框
     */
    public void setMajorCategorySelect(List<CommonPopEntity> data) {
        commonlist = data;
        majorCategory.setShowThreeRecycler(false);
        majorCategory.setDismiss(false);
        majorCategory.setData(commonlist, 0);
    }

    /**
     * 专家库列表所属类别筛选框
     */
    public void setCategoryTypeSelect(List<PickSelectEntity> data) {
        typeData.clear();
        typeData.addAll(data);
    }

    public void delete(int position) {
        pickExpertAdapter.removeItem(position);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.right_view:
                PickExpertEditActivity.start(this,"");
                break;
            case R.id.tv_search_delete:
                binding.includeSearch.etView.setText("");
                searchName = "";
                initFilterData();
                break;
            case R.id.search_text:
                if (TextUtils.isEmpty(binding.includeSearch.etView.getText().toString())) {
                    MToast.showToast(PickExpertListActivity.this, "请输入关键字");
                    return;
                }
                searchName = binding.includeSearch.etView.getText().toString();
                initFilterData();
                break;
            case R.id.tv_type:
                if (TextUtils.isEmpty(typeName)) {
                    typeName = "所属类别";
                    typePopWindow.setDefItem();
                }
                updateChooseTextStatus(binding.tvType, "所属类别".equals(typeName) ? -1 : -2, typeName);
                new Handler().postDelayed(() -> typePopWindow.showPopwindow(binding.tvType, 0, 0), 300);
                typePopWindow.setData(typeData, false);
                break;
            case R.id.tv_address:
                if (scrData == null) {
                    viewModel.getProvinceData();
                    return;
                }
                if (TextUtils.isEmpty(areaName)) {
                    areaName = "工作地区";
                }
                updateChooseTextStatus(binding.tvAddress, TextUtils.isEmpty(areaCode) && TextUtils.isEmpty(cityNo) ? -1 : -2, areaName);
                new Handler().postDelayed(() -> mAddressPop.showPopwindow0(binding.tvAddress), 200);
                break;
            case R.id.tv_major_category:
                if (TextUtils.isEmpty(majorName)) {
                    majorName = "评标专业";
                }
                updateChooseTextStatus(binding.tvMajorCategory, "评标专业".equals(majorName) ? -1 : -2, majorName);
                new Handler().postDelayed(() -> majorCategory.showPopwindow0(binding.tvMajorCategory), 200);
                break;
            case R.id.img_back_top:
                binding.imgBackTop.setVisibility(View.GONE);
                binding.recyclerView.scrollToPosition(0);
                binding.scrollview.scrollTo(0, 0);
                break;
        }
    }

    /**
     * 更新选项颜色
     */
    private void updateChooseTextStatus(PickPopWindowView pickPopWindowView, int value, String name) {
        if (!TextUtils.isEmpty(name)) {
            if (name.length() > 4) {
                name = name.substring(0, 4) + "...";
            }
        }
        if (value == -1 || value == -2) {
            binding.popLine.setVisibility(View.VISIBLE);
            pickPopWindowView.setChooseData(R.drawable.member_pop_blue_bg2, R.mipmap.ic_up_arrow_n, R.color.color_333333, true, name);
        } else if (value == 0) {
            binding.popLine.setVisibility(View.GONE);
            pickPopWindowView.setChooseData(R.drawable.search_bg, R.mipmap.ic_down_arrow_n, R.color.color_333333, false, name);
        } else {
            binding.popLine.setVisibility(View.GONE);
            pickPopWindowView.setChooseData(R.drawable.search_new_blue_bg_10, R.mipmap.icon_down_red, R.color.color_main, false, name);
        }
    }
}